<?php
namespace apiadmin\modules\v1\controllers\group;

use apiadmin\modules\v1\controllers\CoreController;
use common\bonus\SpeedBonus;
use common\models\Article;
use common\models\GroupDetail;
use common\models\GroupFinalist;
use common\models\GroupWinning;
use common\models\Member;
use common\models\TradeCommodity;
use common\models\TradeSpeedBonus;

class  GroupController extends CoreController
{
    /*
    *拼团列表
*/
    public function actionList()
    {

        $where  = $this->formartWhere();

        $params = array(
            'field'	=> ['*'],
            'order' => 'group_time desc',
            'page'	=> $this->request('page','1'),
            'limit' => $this->request('page_size',10),
        );
        $list =GroupDetail::dataList($where,$params,['home_list']);
        $pages = GroupDetail::$pages;

        $this->out('拼团列表',$list,array('pages'=>$pages));
    }

    public function actionGroupMember(){
        $where  = $this->formartWhere();

        $params = array(
            'field'	=> ['member_id','member_name','member_mobile','member_email'],
            'page'	=> $this->request('page','1'),
            'limit' => $this->request('page_size',10),
            'group_type'=>$this->request('group_type'),
            'group_detail_id' =>$this->request('group_detail_id'),
            'type'            =>  $this->request('type'),
        );

        $list =Member::groupMember($where,$params,['winning_id']);
        $pages = Member::$pages;

        $this->out('拼团人员列表',$list,array('pages'=>$pages));
    }



    public function  actionSetMember(){
        $where  = $this->formartWhere();
        $fina   = $this->request('fina','');
        $winning = $this->request('winning');

       $group_detail_id =$this->request('group_detail_id');
       try {
           $transaction = \Yii::$app->db->beginTransaction();
           $id = '';
           if ($winning) {
               $idArr = json_decode($winning, true);
               $result = GroupWinning::insertAll($idArr, $group_detail_id);
               $id = implode(',', array_values($idArr));
           }
           $id_arr=[];
           if ($fina){
               $idArr = json_decode($fina, true);
               $id_arr = GroupFinalist::insertAll($idArr, $group_detail_id);
           }
           $data = GroupDetail::getOne(['group_detail_id' => $group_detail_id]);
           $winning_id = $data['winning_id'];
           $finalist_id = $data['finalist_id'];

           if ($id) {
               if ($winning_id) {
                   $winning_id = $data['winning_id'] . ',' . $id;
               }else {
                   $winning_id=$id;
               }
           }

           if ($id_arr){
               if ($data['finalist_id']) {
                   $finalist_id = $data['finalist_id'] . ',' . implode(',',$id_arr);
               }else {
                   $finalist_id =implode(',',$id_arr);
               }
           }

           GroupDetail::updateAll(['winning_id'=>$winning_id,'finalist_id'=>$finalist_id],['group_detail_id' => $group_detail_id]);
           $transaction->commit();
           $this->out('提交成功');

       }catch (\Exception $e){
           $transaction->rollback();
           $this->error($e->getMessage());
       }
    }

    //组装条件
    public function formartWhere()
    {
        $where = [];
        $whereAnd = [];
        $searchKeys = json_decode($this->request('search'),1);

        if(!$searchKeys) return array('where'=>$where,'whereAnd'=>$whereAnd);
        foreach($searchKeys as $k=>$val)
        {
            if(!$val) continue;
            if($k=='date')
            {
                if(!$val['0'] || !$val['1']) continue;
                $whereAnd[] = ['between', 'group_time', date('Y-m-d',strtotime($val[0])),date('Y-m-d',strtotime($val[1]))];
            }elseif ($k=='member_name') {
                $whereAnd[] = ['like',$k,$val];
            }else
            {
                $where[$k] = $val;
            }
        }

        return array('where'=>$where,'and'=>$whereAnd);
    }

    public function actionListInfo()
    {

        $params = array(
            'field'	=> ['*'],
            'order' => 'create_time desc',
            'page'	=> $this->request('page','1'),
            'limit' => $this->request('page_size',10),
        );
        $where['where']=['type'=>3];
        $list =TradeCommodity::dataList($where,$params);
        $pages = GroupDetail::$pages;

        $this->out('拼团列表',$list,array('pages'=>$pages));
    }


    public function actionInfo()
    {
        if(!$id = $this->request('commodity_id')) $this->error('参数错误');
        $data = TradeCommodity::getOne(['commodity_id'=>$id]);
        $this->out('拼团活动:'.$id,$data);
    }

    public function actionSave(){
        $model = new TradeCommodity;
        if($id = $this->request('commodity_id'))
            $model = TradeCommodity::findOne($id);
        else
            $model->create_time = date('Y-m-d H:i:s',time());

        $data = $this->request;
        $model->update_time = date('Y-m-d H:i:s',time());
        $model->type        =3;
        $model->money_down  =0;
        if($model->load($data,'') && $model->save())
        {
            $this->out('操作成功');
        }

        $this->error('操作失败');
    }

    public function actionSetAlgebra(){
       $dataArr =$this->request;
        unset($dataArr['auth_key']);
       if (!$dataArr){
           return $this->error('请传数据');
       }
       $data = json_decode($dataArr['data'],true);
      
        foreach ($data as $k=>$v) {
            $dataInfo ['level']     =$v['level'];
            $dataInfo['rate']       = $v['rate'];
            $v['pintuan']           =$v['pintuan']?1:0;
            $dataInfo['condition']  ='child_num >= '.$v['child_num'].' and grade > 0 and pintuan = '. $v['pintuan'];
            $dataInfo['bonus_type'] =2;
            SpeedBonus::updateAll($dataInfo,'id='.$v['id']);
        }
        $this->out('操作成功');
    }

    public function actionGetAlgebra(){
        $data = TradeSpeedBonus::getAll(['model_id'=>5]);
        foreach ($data as $k=>&$v) {
           $conditions=explode('and',$v['condition']);
           foreach ($conditions as $ck=>$cv){
               if (strstr($cv,'child_num')){
                   $child_num=explode('>=',$cv);
                  $v['child_num']=$child_num[1]?trim($child_num[1]):'';
               }elseif (strstr($cv,'pintuan '))
               {
                   $pintuan=explode('=',$cv);
                   $v['pintuan']=$pintuan[1]==1?true:false;

               }
               unset($v['condition']);
           }
        }
        $this->out('拼团代数配置',$data);
    }
}